//
//  WCNImageCCell.m
//  WCN
//
//  Created by 杨鑫 on 15/6/4.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNImageCCell.h"
//
#import "Macros.h"

@interface WCNImageCCell () <UIScrollViewDelegate>

@end

@implementation WCNImageCCell

- (void)awakeFromNib {
    // Initialization code
    self.scrollView.delegate = self;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.userInteractionEnabled = YES;
    _imageView = imageView;
    [self.scrollView addSubview:imageView];
}

- (void)setImage:(UIImage *)image
{
    CGFloat scaleX=1.0, scaleY=1.0, scale;
    CGSize size = image.size;
    if (size.width > self.frame.size.width) {
        scaleX = self.frame.size.width/size.width;
    }
    if (size.height > self.frame.size.height) {
        scaleY = self.frame.size.height/size.height;
    }
    scale = MIN(scaleX, scaleY);
    
    [self.scrollView setZoomScale:scale animated:NO];
    size.width *= scale;
    size.height *= scale;

    self.scrollView.contentSize = size;
    self.imageView.frame = CGRectMake(0, 0, size.width, size.height);
    self.imageView.image = image;

    CGSize boundsSize = CGSizeMake(kScreenWidth, kScreenHeight);
    CGPoint centerPoint = CGPointMake(size.width/2, size.height/2);
    if (size.width <= boundsSize.width) {
        centerPoint.x = boundsSize.width/2;
    }
    if (size.height <= boundsSize.height) {
        centerPoint.y = boundsSize.height/2;
    }
    self.imageView.center = centerPoint;
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGSize boundsSize = scrollView.bounds.size;
    CGRect imgFrame = self.imageView.frame;
    CGSize contentSize = scrollView.contentSize;
    
    CGPoint centerPoint = CGPointMake(contentSize.width/2, contentSize.height/2);
    
    // center horizontally
    if (imgFrame.size.width <= boundsSize.width)
    {
        centerPoint.x = boundsSize.width/2;
    }
    
    // center vertically
    if (imgFrame.size.height <= boundsSize.height)
    {
        centerPoint.y = boundsSize.height/2;
    }
    
    self.imageView.center = centerPoint;
}

@end
